package com.vcc.web.core.component;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.vcc.core.exception.ProgramException;
import com.vcc.web.core.config.SmsConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class SmsComponent {

    private Logger logger = LoggerFactory.getLogger(SmsComponent.class);

    @Autowired
    private SmsConfig smsConfig;
    @Autowired
    private RedisComponent redisComponent;
    @Value("${spring.profiles.active}")
    private String activeProfile;

    public Boolean sendActiveEmail(String email, Long userId) {
        String code = UUID.randomUUID().toString().replace("-", "");
        redisComponent.set("active:" + code, userId.toString(), 1L, TimeUnit.DAYS);
        return sendActiveEmail(email, (code));
    }

    public Boolean sendActiveEmail(String email, String token) {
        return sendEmailCode(email, token, smsConfig.getActiveCode(), "激活账号", getHtmlStr("激活账号", smsConfig.getActiveUrl() + token, "此操作将会自动激活您的账号"));
    }

    public Boolean sendUpdatePasswordEmail(String email, String token) {
        return sendEmailCode(email, token, smsConfig.getUpdatePasswordCode(), "重置密码", getHtmlStr("重置密码", smsConfig.getForgotUrl() + token, "此操作将会重置您的登录密码"));
    }

    public Boolean sendAccountCodeEmail(String email, String code) {
        return sendEmailCode(email, code, smsConfig.getVerifyCode(), "邮箱验证码", getCodeHtmlStr("邮箱验证码", code));
    }

    private String getHtmlStr(String title, String url, String info) {
        return "<head>\n" +
                "    <base target=\"_blank\" />\n" +
                "    <style type=\"text/css\">::-webkit-scrollbar{ display: none; }</style>\n" +
                "    <style id=\"cloudAttachStyle\" type=\"text/css\">#divNeteaseBigAttach, #divNeteaseBigAttach_bak{display:none;}</style>\n" +
                "    <style id=\"blockquoteStyle\" type=\"text/css\">blockquote{display:none;}</style>\n" +
                "    <style type=\"text/css\">\n" +
                "        body{font-size:14px;font-family:arial,verdana,sans-serif;line-height:1.666;padding:0;margin:0;overflow:auto;white-space:normal;word-wrap:break-word;min-height:100px}\n" +
                "        td, input, button, select, body{font-family:Helvetica, 'Microsoft Yahei', verdana}\n" +
                "        pre {white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word;width:95%}\n" +
                "        th,td{font-family:arial,verdana,sans-serif;line-height:1.666}\n" +
                "        img{ border:0}\n" +
                "        header,footer,section,aside,article,nav,hgroup,figure,figcaption{display:block}\n" +
                "        blockquote{margin-right:0px}\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body tabindex=\"0\" role=\"listitem\">\n" +
                "<table width=\"700\" border=\"0\" align=\"center\" cellspacing=\"0\" style=\"width:700px;\">\n" +
                "    <tbody>\n" +
                "    <tr>\n" +
                "        <td>\n" +
                "            <div style=\"width:700px;margin:0 auto;border-bottom:1px solid #ccc;margin-bottom:30px;\">\n" +
                "                <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"700\" height=\"39\" style=\"font:12px Tahoma, Arial, 宋体;\">\n" +
                "                    <tbody><tr><td width=\"210\"></td></tr></tbody>\n" +
                "                </table>\n" +
                "            </div>\n" +
                "            <div style=\"width:680px;padding:0 10px;margin:0 auto;\">\n" +
                "                <div style=\"line-height:1.5;font-size:14px;margin-bottom:25px;color:#4d4d4d;\">\n" +
                "                    <strong style=\"display:block;margin-bottom:15px;\">尊敬的用户您好！</strong>\n" +
                "                    <strong style=\"display:block;margin-bottom:15px;\">\n" +
                "                        您正在进行<span style=\"color: red\">" + title + "</span>操作，<a style=\"color:#f60;font-size: 24px\" href='" + url + " '>请点击当前连接</a>，以完成操作。\n" +
                "                    </strong>\n" +
                "                </div>\n" +
                "                <div style=\"margin-bottom:30px;\">\n" +
                "                    <small style=\"display:block;margin-bottom:20px;font-size:12px;\">\n" +
                "                        <p style=\"color:#747474;\">\n" +
                "                            注意：" + info + "。如非本人操作，请及时登录并修改密码以保证帐户安全\n" +
                "                            <br>（工作人员不会向你索取链接，请勿泄漏！)\n" +
                "                        </p>\n" +
                "                    </small>\n" +
                "                </div>\n" +
                "            </div>\n" +
                "            <div style=\"width:700px;margin:0 auto;\">\n" +
                "                <div style=\"padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;\">\n" +
                "                    <p>此为系统邮件，请勿回复<br>\n" +
                "                        请保管好您的邮箱，避免账号被他人盗用\n" +
                "                    </p>\n" +
                "                </div>\n" +
                "            </div>\n" +
                "        </td>\n" +
                "    </tr>\n" +
                "    </tbody>\n" +
                "</table>\n" +
                "</body>";
    }

    private String getCodeHtmlStr(String title, String code) {
        return "<head>\n" +
                "                <base target=\"_blank\" />\n" +
                "                <style type=\"text/css\">::-webkit-scrollbar{ display: none; }</style>\n" +
                "                <style id=\"cloudAttachStyle\" type=\"text/css\">#divNeteaseBigAttach, #divNeteaseBigAttach_bak{display:none;}</style>\n" +
                "                <style id=\"blockquoteStyle\" type=\"text/css\">blockquote{display:none;}</style>\n" +
                "                <style type=\"text/css\">\n" +
                "                    body{font-size:14px;font-family:arial,verdana,sans-serif;line-height:1.666;padding:0;margin:0;overflow:auto;white-space:normal;word-wrap:break-word;min-height:100px}\n" +
                "                    td, input, button, select, body{font-family:Helvetica, 'Microsoft Yahei', verdana}\n" +
                "                    pre {white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word;width:95%}\n" +
                "                    th,td{font-family:arial,verdana,sans-serif;line-height:1.666}\n" +
                "                    img{ border:0}\n" +
                "                    header,footer,section,aside,article,nav,hgroup,figure,figcaption{display:block}\n" +
                "                    blockquote{margin-right:0px}\n" +
                "                </style>\n" +
                "                </head>\n" +
                "                <body tabindex=\"0\" role=\"listitem\">\n" +
                "                <table width=\"700\" border=\"0\" align=\"center\" cellspacing=\"0\" style=\"width:700px;\">\n" +
                "                <tbody>\n" +
                "                <tr>\n" +
                "                    <td>\n" +
                "                        <div style=\"width:700px;margin:0 auto;border-bottom:1px solid #ccc;margin-bottom:30px;\">\n" +
                "                            <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"700\" height=\"39\" style=\"font:12px Tahoma, Arial, 宋体;\">\n" +
                "                                <tbody><tr><td width=\"210\"></td></tr></tbody>\n" +
                "                            </table>\n" +
                "                        </div>\n" +
                "                        <div style=\"width:680px;padding:0 10px;margin:0 auto;\">\n" +
                "                            <div style=\"line-height:1.5;font-size:14px;margin-bottom:25px;color:#4d4d4d;\">\n" +
                "                                <strong style=\"display:block;margin-bottom:15px;\">尊敬的用户您好！</strong>\n" +
                "                                <strong style=\"display:block;margin-bottom:15px;\">\n" +
                "                                    您正在进行<span style=\"color: red\">" + title + "</span>操作，您的验证码是: <span style=\"color:#f60;font-size: 24px\">" + code + "</span>。\n" +
                "                                </strong>\n" +
                "                            </div>\n" +
                "                            <div style=\"margin-bottom:30px;\">\n" +
                "                                <small style=\"display:block;margin-bottom:20px;font-size:12px;\">\n" +
                "                                    <p style=\"color:#747474;\">\n" +
                "                                        注意：如非本人操作，请及时登录并修改密码以保证帐户安全\n" +
                "                                        <br>（工作人员不会向你索取验证码，请勿泄漏！)\n" +
                "                                    </p>\n" +
                "                                </small>\n" +
                "                            </div>\n" +
                "                        </div>\n" +
                "                        <div style=\"width:700px;margin:0 auto;\">\n" +
                "                            <div style=\"padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;\">\n" +
                "                                <p>此为系统邮件，请勿回复<br>\n" +
                "                                    请保管好您的邮箱，避免账号被他人盗用\n" +
                "                                </p>\n" +
                "                            </div>\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "                </tbody>\n" +
                "                </table>\n" +
                "                </body>";
    }


    public Boolean sendEmailCode(String email, String token, String code, String title, String content) {
        IClientProfile profile;
        if (activeProfile.equals("prod")) {
            try {
                // 如果是除杭州region外的其它region（如新加坡region）， 需要做如下处理, 这个居然是通过工单文过来的!!!
                DefaultProfile.addEndpoint("dm.ap-southeast-1.aliyuncs.com", "ap-southeast-1", "Dm", "dm.ap-southeast-1.aliyuncs.com");
            } catch (ClientException e) {
                e.printStackTrace();
            }
            profile =
                    DefaultProfile.getProfile("ap-southeast-1", smsConfig.getAccessKeyId(), smsConfig.getAccessKeySecret());
        } else {

            profile = DefaultProfile.getProfile("cn-hangzhou", smsConfig.getAccessKeyId(), smsConfig.getAccessKeySecret());
        }

        IAcsClient client = new DefaultAcsClient(profile);
        SingleSendMailRequest request = new SingleSendMailRequest();
        try {
            request.setAccountName(smsConfig.getEmailAddress()); //控制台创建的发信地址
            request.setFromAlias(smsConfig.getFromAlias()); //发信人昵称
            request.setAddressType(1);
            request.setTagName(code); //控制台创建的标签
            request.setReplyToAddress(true);
            //可以给多个收件人发送邮件，收件人之间用逗号分开，批量发信建议使用BatchSendMailRequest方式
            request.setToAddress(email); //目标地址
            request.setSubject(title); //邮件主题
            //        2.1、写html开始内容
//        3、拼接html
            request.setHtmlBody(content); //邮件正文
//            request.setHtmlBody(""); //邮件正文
            client.getAcsResponse(request);
            return true;
        } catch (ServerException e) {
            logger.error("ErrCode", e);
            throw new ProgramException("发送失败");
        } catch (ClientException e) {
            logger.error("ErrCode", e);
            throw new ProgramException("发送失败");
        }
    }
}
